"""
Original GCR-NCCL Extension Implementation.

This extension wraps the existing GCR-NCCL build system and test framework.
"""

import json
import os
import subprocess
import logging
from pathlib import Path
from typing import Dict, List, Optional, Any

from gcr_solver_manager.extensions.base_extension import SolverExtension
from gcr_solver_manager.extensions.base_builder import BuilderInterface, BuildConfig, BuildResult, BuildDependencyResult
from gcr_solver_manager.extensions.base_runner import RunnerInterface, RunConfig, RunResult, EnvironmentResult  
from gcr_solver_manager.extensions.base_validator import ValidatorInterface, ValidationConfig, ValidationResult
from .builder import OriginalGCRBuilder
from .runner import OriginalGCRRunner
from .validator import OriginalGCRValidator

logger = logging.getLogger(__name__)


class OriginalGCRExtension(SolverExtension):
    """Extension for Original GCR-NCCL solver framework."""
    
    def __init__(self, source_dir: Optional[Path] = None):
        """Initialize the Original GCR extension."""
        self.source_dir = source_dir or Path("../").resolve()
        self._builder = None
        self._runner = None
        self._validator = None
    
    @property
    def name(self) -> str:
        """Extension unique identifier."""
        return "original-gcr-nccl"
    
    @property
    def version(self) -> str:
        """Extension version string."""
        return "1.0.0"
    
    @property
    def supported_frameworks(self) -> List[str]:
        """List of supported framework names."""
        return ["original", "gcr-nccl"]
    
    @property
    def supported_solvers(self) -> List[str]:
        """List of supported solver types."""
        return ["gcr", "ca-gcr", "gmres", "bca-gmres"]
    
    def get_builder(self) -> BuilderInterface:
        """Return builder instance for this extension."""
        if self._builder is None:
            self._builder = OriginalGCRBuilder(self.source_dir)
        return self._builder
    
    def get_runner(self) -> RunnerInterface:
        """Return runner instance for this extension."""
        if self._runner is None:
            self._runner = OriginalGCRRunner(self.source_dir)
        return self._runner
    
    def get_validator(self) -> ValidatorInterface:
        """Return validator instance for this extension."""
        if self._validator is None:
            self._validator = OriginalGCRValidator()
        return self._validator
    
    def get_config_schema(self) -> Dict[str, Any]:
        """Return JSON schema for configuration validation."""
        schema_path = Path(__file__).parent / "config_schema.json"
        if schema_path.exists():
            with open(schema_path, 'r') as f:
                return json.load(f)
        return {}
    
    def can_handle_config(self, config_path: Path) -> bool:
        """Check if extension can handle given configuration."""
        # Check if this is an original GCR configuration
        # by looking at file structure or content
        
        if not config_path.exists():
            return False
            
        # Check if it's an XML configuration file (original format)
        if config_path.suffix.lower() == '.xml':
            return True
        
        # Check if it's in the original GCR source directory structure
        try:
            relative_path = config_path.resolve().relative_to(self.source_dir)
            # Check if it's not specifically in hybrid or kokkos directories
            parts = relative_path.parts
            if 'hybrid' in parts or 'kokkos' in parts:
                return False
            return True
        except ValueError:
            # Path is not relative to source directory
            return False
    
    def initialize(self, gsm_services: Optional['GSMServices'] = None) -> bool:
        """Initialize extension with GSM services."""
        try:
            # Validate that source directory exists and has build scripts
            if not self.source_dir.exists():
                logger.error(f"Source directory not found: {self.source_dir}")
                return False
            
            build_script = self.source_dir / "scripts" / "build.sh"
            if not build_script.exists():
                logger.error(f"Build script not found: {build_script}")
                return False
            
            logger.info(f"Original GCR extension initialized with source dir: {self.source_dir}")
            return True
            
        except Exception as e:
            logger.error(f"Failed to initialize Original GCR extension: {e}")
            return False
    
    def cleanup(self) -> bool:
        """Cleanup extension resources."""
        # No specific cleanup needed for original GCR
        return True